﻿#include "mytitlebar.h".h"
#include <QLayout>
#include <QLabel>
#include <QMouseEvent>
#include <QApplication>
#include <QScreen>
#include <QDesktopWidget>
//#include "mainwindow.h"

MyTitleBar::MyTitleBar(QWidget *parent)
    :QDialog(parent,Qt::FramelessWindowHint)    //无窗体
{
    //setWindowFlags(Qt::FramelessWindowHint);  //无窗体
    //MainWindow *mwin=new MainWindow;
    //initControl(mwin);
    initControl();
    initForm();
}

bool MyTitleBar::eventFilter(QObject *obj, QEvent *evt)
{
    static QPoint mousePoint;
    static bool mousePressed = false;

    QMouseEvent *event = static_cast<QMouseEvent *>(evt);
    if (event->type() == QEvent::MouseButtonPress) {
        if (event->button() == Qt::LeftButton) {
            mousePressed = true;
            mousePoint = event->globalPos() - this->pos();
            return true;
        }
    } else if (event->type() == QEvent::MouseButtonRelease) {
        mousePressed = false;
        return true;
    } else if (event->type() == QEvent::MouseMove) {
        if (!isWinMaximized && mousePressed && (event->buttons() && Qt::LeftButton) /*&& obj == this->widgetTitle*/) { //移动窗体限定在标题栏
            this->move(event->globalPos() - mousePoint);
            return true;
        }
    } else if (event->type() == QEvent::MouseButtonDblClick) {
        if (this->btnWin_Max->isVisible() /*&& obj == this->widgetTitle*/) {
            this->winMax();
            return true;
        }
    }

    return QWidget::eventFilter(obj, evt);
}

void MyTitleBar::setLogoAndTitle(const QString &imageFile, const QString &title)
{
    QPixmap pix=QPixmap(imageFile);
    this->labIco->setScaledContents(true);  //图片自适应label控件
    this->labIco->setPixmap(pix);

    this->labTitle->setText(title);
}

void MyTitleBar::setMainWidget(QWidget *mainWidget)
{
    //只能设置一个主窗体
    //if(this->mainWidget==0){
        //this->widget->layout()->addWidget(mainWidget);  //将子窗体添加到布局
        //resize(mainWidget->width(),mainWidget->height()+this->widgetTitle->height());   //自动设置大小

    //this->mainWidget=mainWidget;
    this->verticalLayout->addWidget(mainWidget);
    //}
}

void MyTitleBar::initControl()
{
    //【界面布局】——begin，纵向布局，上方标题栏，下方mainWidget
    verticalLayout = new QVBoxLayout(this);
    verticalLayout->setMargin(0);
    verticalLayout->setSpacing(0);

    QWidget *widgetTitle = new QWidget(this);
    widgetTitle->setMinimumSize(QSize(0, 30));//标题栏高度30
    widgetTitle->setMaximumSize(QSize(QWIDGETSIZE_MAX,30));

    verticalLayout->addWidget(widgetTitle);

    //上方标题栏。水平布局（widgetTitle的布局），从左至右:logo+title+skin+min+max+close,
    QHBoxLayout *horizontalLayout=new QHBoxLayout(widgetTitle);
    horizontalLayout->setSpacing(0);
    horizontalLayout->setMargin(0);
    labIco=new QLabel(widgetTitle);

    labIco->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding); //控件水平方向指定最小，垂直方向延伸到最大
    labIco->setMinimumSize(QSize(30,0));        //宽30，高由widgetTitle高确定
    labIco->setMaximumSize(QSize(30,QWIDGETSIZE_MAX));
    labIco->setAlignment(Qt::AlignCenter);
    //labIco->setFrameShape(QFrame::Box);
    //labIco->setText("Logo");

    labTitle=new QLabel(widgetTitle);   //宽高由其他确定
    labTitle->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    labTitle->setAlignment(Qt::AlignCenter);
    //labTitle->setFrameShape(QFrame::Box);
    //labTitle->setText("This is title");

    horizontalLayout->addWidget(labIco);       //logo
    horizontalLayout->addWidget(labTitle);     //title

    /*
    QWidget *widgetMenu=new QWidget(widgetTitle);
    widgetMenu->setMinimumSize(QSize(30,0));
    widgetMenu->setMaximumSize(QSize(30,16777215));
    */

    btnWin_Skin=new QPushButton(widgetTitle);
    btnWin_Skin->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding); //控件水平方向指定最小，垂直方向延伸到最大
    btnWin_Skin->setMinimumSize(QSize(30,0));
    btnWin_Skin->setMaximumSize(QSize(30,QWIDGETSIZE_MAX));

    btnWin_Min=new QPushButton(widgetTitle);
    btnWin_Min->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding); //控件水平方向指定最小，垂直方向延伸到最大
    btnWin_Min->setMinimumSize(QSize(30,0));
    btnWin_Min->setMaximumSize(QSize(30,QWIDGETSIZE_MAX));

    btnWin_Max=new QPushButton(widgetTitle);
    btnWin_Max->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding); //控件水平方向指定最小，垂直方向延伸到最大
    btnWin_Max->setMinimumSize(QSize(30,0));
    btnWin_Max->setMaximumSize(QSize(30,QWIDGETSIZE_MAX));

    btnWin_Close=new QPushButton(widgetTitle);
    btnWin_Close->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding); //控件水平方向指定最小，垂直方向延伸到最大
    btnWin_Close->setMinimumSize(QSize(30,0));
    btnWin_Close->setMaximumSize(QSize(30,QWIDGETSIZE_MAX));

    horizontalLayout->addWidget(btnWin_Skin);     //skin
    horizontalLayout->addWidget(btnWin_Min);      //min
    horizontalLayout->addWidget(btnWin_Max);      //max
    horizontalLayout->addWidget(btnWin_Close);    //close

    //下方mainWidget
    //mainWidget->setMinimumSize(QSize(640,480));   //只设置最小。最大依据窗口变化。默认最小640*480
    //mainWidget->setMaximumSize(QSize(16777215,100));
    //verticalLayout->addWidget(mainWidget);
    //【界面布局】——end

    //标题栏的事件过滤器
    //this->installEventFilter(this);
    widgetTitle->installEventFilter(this);    //标题栏绑定事件过滤器，监听鼠标移动。点击标题栏移动窗体，双击最大化。

    //按钮的信号槽
    connect(this->btnWin_Min,&QPushButton::clicked,this,&MyTitleBar::winMin);
    connect(this->btnWin_Max,&QPushButton::clicked,this,&MyTitleBar::winMax);
    connect(this->btnWin_Close,&QPushButton::clicked,this,&MyTitleBar::winClose);

    //初始化值
    winLocation=this->geometry();                       //窗口位置
    isWinMaximized=false;                               //未最大化
}

void MyTitleBar::initForm()
{
    //
    IconHelper::Instance()->setIcon(this->btnWin_Skin,QChar(0xf0d7));
    IconHelper::Instance()->setIcon(this->btnWin_Min,QChar(0xf068));
    IconHelper::Instance()->setIcon(this->btnWin_Max,QChar(0xf2d0));
    IconHelper::Instance()->setIcon(this->btnWin_Close,QChar(0xf00d));
}

void MyTitleBar::winMin()
{
    this->showMinimized();
}

void MyTitleBar::winMax()
{
    if(isWinMaximized){                                     //如果已经最大化，则还原到原位置
        setMinimumSize(0,0);                                //允许拖动改变大小
        setMaximumSize(QSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX));

        this->setGeometry(winLocation);                     //还原到原来位置
        IconHelper::Instance()->setIcon(this->btnWin_Max,QChar(0xf2d0));
    }else{
        winLocation=this->geometry();                       //记录原来位置，然后再最大化

        //this->showMaximized();                            //直接最大化会覆盖任务栏（或在任务栏之后）
        this->setGeometry(QApplication::desktop()->availableGeometry());
        this->setFixedSize(this->width(), this->height());  //最大化后不允许拖动改变大小（右下角处）
        IconHelper::Instance()->setIcon(this->btnWin_Max,QChar(0xf2d2));
    }
    isWinMaximized=!isWinMaximized;                         //最大化后不允许移动窗口（标题栏处）
}

void MyTitleBar::winClose()
{
    this->close();      //关闭Dialog（其内的widget也会释放）
}

#include<QFontDatabase>
#include<QDebug>
#include<QPainter>

IconHelper *IconHelper::self=0;
IconHelper::IconHelper(QObject *parent) : QObject(parent)
{
    int fontId = QFontDatabase::addApplicationFont(":/image/Font Awesome 6 Free-Solid-900.otf");
    QStringList fontName = QFontDatabase::applicationFontFamilies(fontId);

    if (fontName.count() > 0) {
        iconFont = QFont(fontName.at(0));
    } else {
        qDebug() << "load Font Awesome 6 Free-Solid-900.otf error";
    }
}

void IconHelper::setIcon(QLabel *lab, QChar c, quint32 size)
{
    iconFont.setPointSize(size);
    lab->setFont(iconFont);
    lab->setText(c);
}

void IconHelper::setIcon(QAbstractButton *btn, QChar c, quint32 size)
{
    iconFont.setPointSize(size);
    btn->setFont(iconFont);
    btn->setText(c);
}

QPixmap IconHelper::getPixmap(const QString &color, QChar c, quint32 size,
                              quint32 pixWidth, quint32 pixHeight)
{
    QPixmap pix(pixWidth, pixHeight);
    pix.fill(Qt::transparent);

    QPainter painter;
    painter.begin(&pix);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    painter.setPen(QColor(color));
    painter.setBrush(QColor(color));

    iconFont.setPointSize(size);
    painter.setFont(iconFont);
    painter.drawText(pix.rect(), Qt::AlignCenter, c);
    painter.end();

    return pix;
}

QPixmap IconHelper::getPixmap(QToolButton *btn, bool normal)
{
    QPixmap pix;
    int index = btns.indexOf(btn);

    if (index >= 0) {
        if (normal) {
            pix = pixNormal.at(index);
        } else {
            pix = pixDark.at(index);
        }
    }

    return pix;
}

void IconHelper::setStyle(QWidget *widget, const QString &type, int borderWidth, const QString &borderColor,
                          const QString &normalBgColor, const QString &darkBgColor,
                          const QString &normalTextColor, const QString &darkTextColor)
{
    QString strBorder;
    if (type == "top") {
        strBorder = QString("border-width:%1px 0px 0px 0px;padding:%1px %2px %2px %2px;")
                    .arg(borderWidth).arg(borderWidth * 2);
    } else if (type == "right") {
        strBorder = QString("border-width:0px %1px 0px 0px;padding:%2px %1px %2px %2px;")
                    .arg(borderWidth).arg(borderWidth * 2);
    } else if (type == "bottom") {
        strBorder = QString("border-width:0px 0px %1px 0px;padding:%2px %2px %1px %2px;")
                    .arg(borderWidth).arg(borderWidth * 2);
    } else if (type == "left") {
        strBorder = QString("border-width:0px 0px 0px %1px;padding:%2px %2px %2px %1px;")
                    .arg(borderWidth).arg(borderWidth * 2);
    }

    QStringList qss;
    qss.append(QString("QWidget[flag=\"%1\"] QAbstractButton{border-style:none;border-radius:0px;padding:5px;color:%2;background:%3;}")
               .arg(type).arg(normalTextColor).arg(normalBgColor));

    qss.append(QString("QWidget[flag=\"%1\"] QAbstractButton:hover,"
                       "QWidget[flag=\"%1\"] QAbstractButton:pressed,"
                       "QWidget[flag=\"%1\"] QAbstractButton:checked{"
                       "border-style:solid;%2border-color:%3;color:%4;background:%5;}")
               .arg(type).arg(strBorder).arg(borderColor).arg(darkTextColor).arg(darkBgColor));

    widget->setStyleSheet(qss.join(""));
}

void IconHelper::setStyle(QWidget *widget, QList<QToolButton *> btns, QList<int> pixChar,
                          quint32 iconSize, quint32 iconWidth, quint32 iconHeight,
                          const QString &type, int borderWidth, const QString &borderColor,
                          const QString &normalBgColor, const QString &darkBgColor,
                          const QString &normalTextColor, const QString &darkTextColor)
{
    int btnCount = btns.count();
    int charCount = pixChar.count();
    if (btnCount <= 0 || charCount <= 0 || btnCount != charCount) {
        return;
    }

    QString strBorder;
    if (type == "top") {
        strBorder = QString("border-width:%1px 0px 0px 0px;padding:%1px %2px %2px %2px;")
                    .arg(borderWidth).arg(borderWidth * 2);
    } else if (type == "right") {
        strBorder = QString("border-width:0px %1px 0px 0px;padding:%2px %1px %2px %2px;")
                    .arg(borderWidth).arg(borderWidth * 2);
    } else if (type == "bottom") {
        strBorder = QString("border-width:0px 0px %1px 0px;padding:%2px %2px %1px %2px;")
                    .arg(borderWidth).arg(borderWidth * 2);
    } else if (type == "left") {
        strBorder = QString("border-width:0px 0px 0px %1px;padding:%2px %2px %2px %1px;")
                    .arg(borderWidth).arg(borderWidth * 2);
    }

    QStringList qss;
    qss.append(QString("QWidget[flag=\"%1\"] QAbstractButton{border-style:none;border-radius:0px;padding:5px;color:%2;background:%3;}")
               .arg(type).arg(normalTextColor).arg(normalBgColor));

    qss.append(QString("QWidget[flag=\"%1\"] QAbstractButton:hover,"
                       "QWidget[flag=\"%1\"] QAbstractButton:pressed,"
                       "QWidget[flag=\"%1\"] QAbstractButton:checked{"
                       "border-style:solid;%2border-color:%3;color:%4;background:%5;}")
               .arg(type).arg(strBorder).arg(borderColor).arg(darkTextColor).arg(darkBgColor));

    qss.append(QString("QWidget#%1{background:%2;}").arg(widget->objectName()).arg(normalBgColor));

    qss.append(QString("QToolButton{border-width:0px;}"));
    qss.append(QString("QToolButton{background-color:%1;color:%2;}")
               .arg(normalBgColor).arg(normalTextColor));
    qss.append(QString("QToolButton:hover,QToolButton:pressed,QToolButton:checked{background-color:%1;color:%2;}")
               .arg(darkBgColor).arg(darkTextColor));

    widget->setStyleSheet(qss.join(""));

    for (int i = 0; i < btnCount; i++) {
        //存储对应按钮对象,方便鼠标移上去的时候切换图片
        QPixmap pixNormal = getPixmap(normalTextColor, QChar(pixChar.at(i)), iconSize, iconWidth, iconHeight);
        QPixmap pixDark = getPixmap(darkTextColor, QChar(pixChar.at(i)), iconSize, iconWidth, iconHeight);

        btns.at(i)->setIcon(QIcon(pixNormal));
        btns.at(i)->setIconSize(QSize(iconWidth, iconHeight));
        btns.at(i)->installEventFilter(this);

        this->btns.append(btns.at(i));
        this->pixNormal.append(pixNormal);
        this->pixDark.append(pixDark);
    }
}

void IconHelper::setStyle(QFrame *frame, QList<QToolButton *> btns, QList<int> pixChar,
                          quint32 iconSize, quint32 iconWidth, quint32 iconHeight,
                          const QString &normalBgColor, const QString &darkBgColor,
                          const QString &normalTextColor, const QString &darkTextColor)
{
    int btnCount = btns.count();
    int charCount = pixChar.count();
    if (btnCount <= 0 || charCount <= 0 || btnCount != charCount) {
        return;
    }

    QStringList qss;
    qss.append(QString("QToolButton{border-width:0px;}"));
    qss.append(QString("QToolButton{background-color:%1;color:%2;}")
               .arg(normalBgColor).arg(normalTextColor));
    qss.append(QString("QToolButton:hover,QToolButton:pressed,QToolButton:checked{background-color:%1;color:%2;}")
               .arg(darkBgColor).arg(darkTextColor));

    frame->setStyleSheet(qss.join(""));

    for (int i = 0; i < btnCount; i++) {
        //存储对应按钮对象,方便鼠标移上去的时候切换图片
        QPixmap pixNormal = getPixmap(normalTextColor, QChar(pixChar.at(i)), iconSize, iconWidth, iconHeight);
        QPixmap pixDark = getPixmap(darkTextColor, QChar(pixChar.at(i)), iconSize, iconWidth, iconHeight);

        btns.at(i)->setIcon(QIcon(pixNormal));
        btns.at(i)->setIconSize(QSize(iconWidth, iconHeight));
        btns.at(i)->installEventFilter(this);

        this->btns.append(btns.at(i));
        this->pixNormal.append(pixNormal);
        this->pixDark.append(pixDark);
    }
}

bool IconHelper::eventFilter(QObject *watched, QEvent *event)
{
    if (watched->inherits("QToolButton")) {
        QToolButton *btn = (QToolButton *)watched;
        int index = btns.indexOf(btn);
        if (index >= 0) {
            if (event->type() == QEvent::Enter) {
                btn->setIcon(QIcon(pixDark.at(index)));
            } else if (event->type() == QEvent::Leave) {
                if (btn->isChecked()) {
                    btn->setIcon(QIcon(pixDark.at(index)));
                } else {
                    btn->setIcon(QIcon(pixNormal.at(index)));
                }
            }
        }
    }

    return QObject::eventFilter(watched, event);
}
